<template>
	<view class="promote">
		<common-navbar :background="background" titleColor="#ffffff" backIconColor="#ffffff" :customBack="customBack">
		</common-navbar>
		<topBg />
		<view class="qr-code">
			<view class="slogan-container">
				<u-image
					src="https://vkceyugu.cdn.bspapp.com/VKCEYUGU-8acfaa58-aeb5-4502-8309-365d4c6cca4a/df49d93b-152a-4317-94b5-0cbd85fbeea4.png"
					width="472" height="88" />
				<text class="slogan">畅享十项金牌服务，更多佣金任你领</text>
			</view>
			<view class="qr-code-main">
				<uqrcode class="qrcode" v-if="isQrCodeShow&&!iSelectPosterShow" ref="qrcode" canvas-id="qrcode"
					:value="`https://www.gdlzjt.com/xiaolvwxmp/promote/?shareCode=${inviteCode}`" :size="qrcodeSize" />
			</view>
			<button class="share-button" :class="{'disabled':shareQRCodeBtnDisabled}" :disabled="shareQRCodeBtnDisabled"
				@click="save">保存二维码，分享好友</button>
			<canvas style="width: 438px;height: 846px; position: absolute;top:-5000px;" canvas-id="canvasposter"
				id="canvasposter"></canvas>
		</view>
		<friendList />
		<distributionStatus />
		<selectPoster :iSelectPosterShow.sync="iSelectPosterShow" :posterTempFilePathList="posterTempFilePathList"
			@close="iSelectPosterShow = false" />
	</view>
</template>

<script>
	import topBg from "./components/top-bg/topBg.vue";
	import friendList from "./components/friend_list/friendList.vue";
	import distributionStatus from "./components/distribution_status/distributionStatus.vue";
	import selectPoster from "./components/select_poster/selectPoster.vue";
	export default {
		components: {
			topBg,
			friendList,
			distributionStatus,
			selectPoster
		},
		options: {
			styleIsolation: 'shared'
		},
		onShareAppMessage(res) {
			if (res.from === 'button') { // 来自页面内分享按钮
				console.log(res.target)
			}
			return {
				title: '小律懂法邀好友送VIP,快为我助力',
				imageUrl: 'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-8acfaa58-aeb5-4502-8309-365d4c6cca4a/390e106a-35ef-4104-b35d-a43bf66d9c89.png',
				path: `/pages/promote_visitor/promoteVisitor?shareCode=${encodeURIComponent(this.inviteCode)}`
			}
		},
		data() {
			return {
				background: {
					backgroundColor: '#108eef',
				},
				inviteCode: '',
				isQrCodeShow: false,
				iSelectPosterShow: false,
				posterList: [],
				posterTempFilePathList: [],

			}
		},
		async onLoad() {
			await this.$loginStatus;
			await this.getShareCode();
			this.getQRCodePosterList();
		},
		onReady() {

		},
		computed: {
			qrcodeSize() {
				const proportion = 163 / 375;
				return this.$systemInfo.screenWidth * proportion;
			},
			shareQRCodeBtnDisabled() {
				return !this.posterList.length
			}
		},
		methods: {
			async getShareCode() {
				const {
					data
				} = await this.$u.post(this.$restUrl.getShareCode);
				this.inviteCode = data.share_code;
				this.isQrCodeShow = true;
			},
			async getQRCodePosterList() {
				const {
					data
				} = await this.$u.post(this.$restUrl.getQRCodePosterList);
				// this.posterList = data.data.map(item => item.img_url);
				this.posterList = data.data;
			},
			async save() {
				await this.$wx.getPermission('scope.writePhotosAlbum','添加到相册')
				if(this.posterTempFilePathList.length == this.posterList.length){
					return this.iSelectPosterShow = true;
				}
				uni.showLoading({
					title:'正在生成海报',
					mask:true,
				})
				this.posterTempFilePathList = [];
				this.$refs.qrcode.toTempFilePath({
					success: async qrCodeResult => {
						const qrCodeTempFilePath = qrCodeResult.tempFilePath;
						for (let item of this.posterList) {
							console.log(this.posterTempFilePathList);
							const path = await this.drawImage(item, qrCodeTempFilePath);
							this.posterTempFilePathList.push(path);
						}

						this.iSelectPosterShow = true;
						uni.hideLoading();
					},
					fail: qrCodeError => {
						this.$showToast('生成分享海报失败');
						uni.hideLoading();
					}
				});
			},
			drawImage(item, qrCodeTempFilePath) {
				return new Promise((resolve, reject) => {
					uni.getImageInfo({
						src: item.img_url,
						success: (posterResult) => {
							const ctx = uni.createCanvasContext('canvasposter');
							ctx.rect(0, 0, Number(item.poster_width), Number(item.poster_length));
							ctx.fillRect(0, 0, Number(item.poster_width), Number(item.poster_length));
							ctx.drawImage(posterResult.path, 0, 0,Number(item.poster_width), Number(item.poster_length));
							ctx.drawImage(qrCodeTempFilePath, Number(item.x_location), Number(item.y_location), Number(item.qrcode_width), Number(item.qrcode_length));
							ctx.draw(false, () => {
								uni.canvasToTempFilePath({
									canvasId: 'canvasposter',
									success: (canvasResult) => {
										ctx.clearRect(0, 0, Number(item.poster_width), Number(item.poster_length))
										resolve(canvasResult.tempFilePath)
									},
									fail: () => {
										this.$showToast('生成海报失败')
										uni.hideLoading();
									}
								}, this)
							})
						},
						fail: (posterError) => {
							this.$showToast('生成海报失败')
							uni.hideLoading();
						}
					})
				})
			},
			customBack() {
				console.log(getCurrentPages());
				if (getCurrentPages()[getCurrentPages().length - 2]&&getCurrentPages()[getCurrentPages().length - 2]
					.__route__ == 'pages/promote_visitor/promoteVisitor') {
					uni.switchTab({
						url: '/pages/home/home'
					})
				} else {
					uni.navigateBack();
				}
			}
		}
	}
</script>

<style scoped lang="scss">
	@import "./promote.scss";
</style>
